import time, logging, re, os
from selenium.webdriver import ActionChains
from lxml import etree
from selenium import webdriver
from templates.logger import Loggers


class Hourly_weather:

    def __init__(self):
        global logger
        logger = Loggers().make_logger('getHourlyWeather')
        logger.info('Clmib hourly weather start loading........')
        # 配置无头浏览器
        option = webdriver.ChromeOptions()
        option.add_argument("--headless")
        option.add_argument("--disable-gpu")
        option.add_argument("--start-maximized")
        option.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
        global driver
        driver = webdriver.Chrome(chrome_options=option)  # 不打开浏览器
        logger.info(driver)

    def select_city(self, city_code):
        driver.get('http://www.weather.com.cn/weather/%s.shtml' % city_code)  # 获取成都天气
        js_hd = "var q=document.documentElement.scrollTop=940"
        driver.execute_script(js_hd)
        source = driver.page_source
        global html
        html = etree.HTML(source)
        city_name = ''
        province_name = ''
        district_name = ''
        # 这个部分城市只有两级
        try:
            province_name = re.findall('<a href="http://\w+.weather.com.cn" target="_blank">(.*?)</a>', source)[0]  # 省
        except:
            logger.warning('province_name is not exist')

        try:
            city_name = re.findall('target="_blank">(.*?)</a><span>&gt;</span>', source)[0]  # 市
        except:
            logger.warning('city_name is not exist')

        try:
            district_name = re.findall('<span>&gt;</span>\n\s*<span>(.*?)</span>', source)[0]  # 区(有点地方是3个)
        except:
            try:
                # 市区-县
                district_name = re.findall('<span>&gt;</span>\s*<span>(.*?)</span>', source)[0]  # 区
            except:
                logger.warning('district_name is not exist')
        adress = province_name + '-' + city_name + '-' + district_name
        logger.info(adress + "--" + str(city_code))
        return city_code, adress

    def get_content(self):
        Dict_hoursContent = {}
        for i in range(2, 26):
            hours_content = "//*[@id='hourHolder']/*[name()='svg']/*[name()='rect'][%d]" % i  # 获取时间的内容 XPATH
            hourXpath = driver.find_element_by_xpath(hours_content)
            ActionChains(driver).move_to_element(hourXpath).perform()
            source = driver.page_source
            html = etree.HTML(source)  # 解析
            hour_content = html.xpath('//*[@id="hourHolder"]/div[4]/text()')  # 获取指标数
            hour = html.xpath("//*[@id='hourHolder']/div[1]/span[%d]/text()" % i)  # 获取时间
            try:
                Dict_hoursContent[hour[0]] = hour_content[0]
            except:
                logger.warning('%s:00 hour_content is null'%hour[0])
        return Dict_hoursContent

    def get_AQI(self):
        time.sleep(0.5)
        dict_hourAQI = self.get_content()
        logger.info(dict_hourAQI)
        return dict_hourAQI

    def get_temperature(self):  # 相对温度
        time.sleep(0.5)
        driver.find_element_by_xpath('//*[@id="weatherChart"]/div[1]/ul/li[2]').click()  # 温度
        dict_hourTe = self.get_content()
        logger.info(dict_hourTe)
        return dict_hourTe

    def get_humidity(self):
        time.sleep(0.5)
        driver.find_element_by_xpath('//*[@id="weatherChart"]/div[1]/ul/li[3]').click()  # 相对湿度
        dict_hourHu = self.get_content()
        logger.info(dict_hourHu)
        return dict_hourHu

    def get_wind(self):
        time.sleep(0.5)
        driver.find_element_by_xpath('//*[@id="weatherChart"]/div[1]/ul/li[5]').click()  # 相对风力风向
        dict_hourWind = self.get_content()
        logger.info(dict_hourWind)
        return dict_hourWind

    def start(self, city_code=101270101):
        # 通过正则,筛选出区和市,因为区没有AQI
        cityId, address = self.select_city(city_code)
        num = re.findall('1\d{7}(.*)', str(city_code))  # 通过判断最后一位数为0,1
        new_num = int(num[0])
        result = {}
        if new_num == 0 or new_num == 1:
            try:
                dict_hourAQI = self.get_AQI()
                dict_hourTe = self.get_temperature()
                dict_hourHu = self.get_humidity()
                dict_hourWind = self.get_wind()
                result['cityCode'] = cityId
                result['address'] = address
                result['hourAQI'] = dict_hourAQI
                result['hourTe'] = dict_hourTe
                result['hourHu'] = dict_hourHu
                result['hourWind'] = dict_hourWind
                return result
            except:
                logger.error('This is baded')
        else:
            try:
                dict_hourAQI = '该地区的AQI为空,请查看对应的市'
                dict_hourTe = self.get_temperature()
                dict_hourHu = self.get_humidity()
                dict_hourWind = self.get_wind()
                result['cityCode'] = cityId
                result['address'] = address
                result['hourAQI'] = dict_hourAQI
                result['hourTe'] = dict_hourTe
                result['hourHu'] = dict_hourHu
                result['hourWind'] = dict_hourWind
                return result
            except:
                logger.error('This is baded')

    def __del__(self):
        logger.info('Clmib successful')
        driver.quit()


if __name__ == '__main__':
    s = time.clock()
    result = Hourly_weather().start(101270102)
    print(result)
    e = time.clock()
    print(e - s)
